<template>
  <div id="app">
    <div>
      <span>图书名称:</span>
      <input @keyup.enter='OnAdd' v-model.trim="name" type="text" />
    </div>
    <div>
      <button :disabled='flag' @click="OnAdd">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>图书名称</th>
          <th>创建时间</th>
          <th>操作</th>
        </tr>
        <tr v-for="item in list" :key="item.id">
          <td> {{item.id}} </td>
          <td> {{item.name}} </td>
          <td> {{$moment(item.date).format("YYYY-MM-DD")}} </td>
          <td>
            <button @click="del(item.id)" :disabled='list.length === 1?true:false' >删除</button>
            <button @click="edit(item.id)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
axios.defaults.baseURL = 'http://liufusong.top:4000'
export default {
  updated () {
    this.getList()
  },
  data () {
    return {
      list: [],
      name: '',
      flag: false,
      id: '',
      bol: true
    }
  },
  watch: {
    name (newVal) {
      this.judge(newVal)
    }
  },
  created () {
    this.getList()
  },
  methods: {
    async getList () {
      try {
        const res = await axios({
          url: '/books'
        })
        this.list = res.data
      } catch (err) {
        console.log(err.message)
      }
    },
    // 添加修改图书
    OnAdd () {
      if (this.flag) {
        return alert('书名已存在')
      }
      if (this.bol) {
        axios({
          url: '/books',
          method: 'POST',
          data: {
            name: this.name
          }
        })
      } else {
        this.edit2(this.id)
      }

      this.name = ''
    },
    // 删除
    del (id) {
      try {
        axios({
          url: '/books/' + id,
          method: 'DELETE'
        })
      } catch (err) {
        alert('删除失败')
      }
    },
    // 图书是否存在
    async judge (name) {
      const res = await axios({
        url: 'books/book/' + name
      })
      if (res.data.status === 1) {
        this.flag = true
      } else {
        this.flag = false
      }
    },
    // 根据ID查询信息
    async edit (id) {
      const res = await axios({
        url: '/books/' + id
      })
      this.id = res.data.id
      this.name = res.data.name
      this.bol = false
    },
    // 编辑提交图书
    async edit2 (id) {
      await axios({
        url: '/books/' + id,
        method: 'PUT',
        data: {
          name: this.name
        }
      })
    }
  }
}
</script>

<style scoped lang="less"></style>
